package offerbook;

/**
 * @date 2020/3/8 22:55
 */
public class Code12_TwoNbitNumsAdd {
    public static void add(String s1,String s2){
        if(s1 == null || s1.length() == 0 || s2 == null || s2.length() == 0)
            return ;
        int len = Math.max(s1.length(),s2.length());
        byte[] res = new byte[len+1];//考虑进位
        doAdd(s1,s2,res);
        printNum(res);
    }

    private static void printNum(byte[] nums) {
        boolean begin0 = true;
        for (int i = 0; i < nums.length; i++) {
            //begin0 && nums[i]中begin0可以不加，加了优化
            if(begin0 && nums[i] != 0) begin0 = false;
            if(!begin0){
                System.out.print(nums[i]);
            }
        }
        System.out.println();
    }

    private static void doAdd(String s1, String s2, byte[] res) {
        //注意从最高位处理，代表数的最低位！！
        int p1 = s1.length()-1,p2 = s2.length()-1;
        int index = res.length - 1;
        byte over = 0;
        while (p1 >= 0 && p2 >= 0){
            int sum =  s1.charAt(p1--) - '0' + s2.charAt(p2--) - '0' + over;
            if(sum >= 10){
                over = 1;
                sum -= 10;
            }else {
                over = 0;
            }
            res[index--] = (byte) sum;
        }
        //处理单独剩余的那个
        process(s1,p1,res,index,over);
        process(s2,p2,res,index,over);
    }

    private static void process(String s, int p, byte[] res, int index, byte over) {
        while (p >= 0){
            int sum =  s.charAt(p--) - '0' + over;
            if(sum >= 10){
                over = 1;
                sum -= 10;
            }else {
                over = 0;
            }
            res[index--] = (byte) sum;
        }
    }

    public static void main(String[] args) {
        add("199999","11111");
    }
}
